<?php defined('BASEPATH') OR exit('No direct script access allowed');
/**
 * Description: Wap端主控制器
 *
 * @author      Eden
 * @datetime    2016/11/24 21:41
 * @copyright   Beijing CmsTop Technology Co.,Ltd.
 */

include_once(FCPATH . "application/third_party/wechat/include.php");

use Wechat\Loader;

class WX_Controller extends CI_Controller
{

    const NO_LOGIN = '用户未登录';

    protected $options = [];
    protected $setting = [];
    protected $routes = [];

    protected $segment = '';

    protected $error   = '';

    /**
     * 用户 OPENID
     * @var string
     */
    protected $openId = '';

    /**
     * @var int
     */
    protected $userid = 0;

    /**
     * 初始化
     */
    public function __construct()
    {
        parent::__construct();

        // 微信配置
        $this->options = $this->config->item('wechat');                   // 公众账号设置
        $this->setting = $this->config->item('wx_setting');         // 一些业务配置设置
        $this->routes = $this->config->item('wx_routes');           // 路由设置

        if (empty($this->options) || empty($this->options['token'])) {
            throw new Exception('微信配置错误');
        }

        Loader::config($this->options);

        // 检查登录
        $this->_checkAuth();
    }

    /**
     * 检查账号
     */
    private function _checkAuth()
    {
        $this->openId = $this->session->userdata('openId');
        $this->userid = $this->session->userdata('userid');

        // 静默登录
        if (empty($this->openId) || empty($this->userid)) {
            $uri = uri_string();
            if (!in_array($uri, $this->routes['white'])) {
                $gets = $this->input->get();
                if (!empty($gets)) {
                    $uri = 'index';
                }

                $authState = (int) array_search($uri, $this->routes['map']);
                $callback = base_url('/login');
                $oauth = Loader::get('oauth');
                $url = $oauth->getOauthRedirect($callback, $authState, 'snsapi_base');
                redirect($url);
                exit;
            }
        }
        return true;
    }

    /**
     * 获取配置
     * @param $key
     * @param string $field
     * @return bool
     */
    protected function _getConfigByKey($key, $field = '*')
    {
        if (empty($key)) {
            return false;
        }

        $query = $this->db->select($field)
            ->from('setting')
            ->where(array('use' => 'mobile', 'key' => $key))
            ->get();
        return $query->row_array();
    }

    /**
     * 错误输出
     * @param string $error
     */
    protected function outputError($error = '')
    {
        $this->output->send([
            'state' => false,
            'error' => $error
        ]);
    }

    /**
     * 正确输出
     * @param $data
     */
    protected function output($data)
    {
        if (is_array($data)) {
            $this->output->send([
                'state' => true,
                'data' => $data
            ]);
        } else {
            $this->output->send([
                'state' => true,
                'data' => [
                    'msg' => $data
                ]
            ]);
        }
    }

    /**
     * @param string $error
     */
    protected function setError($error = '')
    {
        $this->error = $error;
    }

    /**
     * @return string
     */
    public function getError()
    {
        return $this->error;
    }
}
